<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Course;
use App\Models\CourseRecord;
use App\Models\User;
use App\Models\VipUser;
use App\Services\OrderService;
use App\Services\UserService;
use EasyWeChat\Factory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;

class UserController extends Controller
{
    protected $UserService;
    public function __construct(UserService $UserService)
    {
        $this->UserService = $UserService;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function login(Request $Request){
        if(!$Request->mobile){
            return response()->json(['code' => '403', 'message' => '请输入用户名']);
        }
        if(!$Request->password){
            return response()->json(['code' => '403', 'message' => '请输入密码']);
        }

        $data = User::where('mobile',$Request->mobile)->first();
        if(!$data){
            return response()->json(['code' => '404', 'message' => '账号不存在']);
        }
        // $is = Hash::check($Request->password, $data->password);
        // if(!$is){
        //     return response()->json(['code' => '500', 'message' => '密码错误']);
        // }
        //判断权限
        $data->token = $data->createToken('api')->accessToken;
        $data->type = 'api-refresh';
        return response()->json(['code' => 200, 'message' => 'success','data'=>$data]);
    }

    public function wxlogin(Request $request){
        // 1. 验证小程序传递的code
        $validated = $request->validate([
            'code' => 'required|string',
        ]);
        $code = $validated['code'];

        // 2. 获取微信配置参数
        $appId = 'wx1ff04de8b254879e';//env('WECHAT_APP_APPID');
        $secret = '2f7995457fe54403ecbd8ecc1837d316';//env('WECHAT_APP_SECRET');
        $code2sessionUrl = 'https://api.weixin.qq.com/sns/jscode2session';

        try {
            // 3. 调用微信code2session接口（原生HTTP请求）
            $response = Http::get($code2sessionUrl, [
                'appid' => $appId,
                'secret' => $secret,
                'js_code' => $code,
                'grant_type' => 'authorization_code', // 固定值
            ]);

            // 4. 解析微信返回的JSON数据
            $sessionData = $response->json();

            // 5. 处理微信接口错误（返回errcode则表示失败）
            if (isset($sessionData['errcode']) && $sessionData['errcode'] != 0) {
                return response()->json([
                    'code' => 400,
                    'message' => '微信登录失败：' . $sessionData['errmsg'],
                    'wechat_error' => $sessionData, // 可选：返回微信错误详情用于调试
                ], 400);
            }

            // 6. 提取用户唯一标识openid（核心数据）
            $openid = $sessionData['openid'];
            // unionid（可选，多端统一用户时需要，需满足微信开放平台绑定条件）
            $unionid = $sessionData['unionid'] ?? null;

            // 7. 根据openid查找或创建本地用户
            $user = User::firstOrCreate(
                ['openid' => $openid], // 按openid匹配用户
                [
                    'name' => '微信用户_' . substr($openid, 0, 8), // 默认昵称（截取openid前8位避免重复）
                    'wx_unionid' => $unionid, // 可选：存储unionid
                    'password' => bcrypt(uniqid()), // 必传：Laravel用户表password字段非空，用随机值加密填充
                ]
            );

            // 8. 通过Passport生成access_token
            $token = $user->createToken('wx_token')->accessToken; // 'wechat_mini_login'为Token名称（自定义）

            // 9. 返回登录结果（包含Token和基础用户信息）
            return response()->json([
                'code' => 200,
                'message' => '登录成功',
                'data' =>$token,
            ]);

        } catch (\Exception $e) {
            // 捕获异常（如网络错误、JSON解析失败等）
            return response()->json([
                'code' => 500,
                'message' => '服务器登录异常：' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function codeLogin(Request $Request){
        if(!$Request->mobile){
            return response()->json(['code' => '403', 'message' => '请输入用户名']);
        }
        if(!$Request->code){
            return response()->json(['code' => '403', 'message' => '请输入验证码']);
        }

        $data = User::where('mobile',$Request->mobile)->first();
        if(!$data){
            return response()->json(['code' => '404', 'message' => '账号不存在']);
        }

        $cacheKey = "sms_limit:{$Request->mobile}";
        $iscode = Cache::get($cacheKey);
        if($iscode != $Request->code){
            return response()->json(['code' => '403', 'message' => '验证码错误']);
        }

        //判断权限
        $data->token = $data->createToken('api')->accessToken;
        $data->type = 'api-refresh';
        return response()->json(['code' => 200, 'message' => 'success','data'=>$data]);
    }

    public function index(Request $request)
    {
        $data = User::find(Auth::user()->id);
        $record = CourseRecord::where('user_id',$data->id)->count();
        $course = new OrderService();
        $pay = $course->payCourseCount($data->id,'course');
        $data->isVip = false;
        $vipUser = VipUser::where('user_id',$data->id)->first();
        if($vipUser){
            $t = strtotime($vipUser->end_date);
            if($t > time()){
                $data->isVip = true;
                $data->vip_date = $vipUser->end_date;
            }
        }
        return response()->json(['code' => 200, 'message' => '操作成功','data'=>$data,'record'=>$record,'pay'=>$pay]);
    }

    public function update(Request $request)
    {
        $data = User::find(Auth::user()->id);
        $data->mobile = $request->mobile;
        $data->name = $request->name;
        $data->avatar = $request->avatar;
        $data->save();
        return response()->json(['code' => 200, 'message' => '操作成功','data'=>$data]);
    }

    // 获取手机号接口
    public function getuserphonenumber(Request $request)
    {
        // 验证请求参数
        $request->validate([
            'code' => 'required',
            'encryptedData' => 'required',
            'iv' => 'required',
        ]);

        // 初始化微信小程序实例
        $miniProgram = Factory::miniProgram(config('wechat.mini_program.default'));

        try {
            // 1. 通过 code 换取 session_key 和 openid
            $session = $miniProgram->auth->session($request->code);
            if (isset($session['errcode'])) {
                return response()->json([
                    'success' => false,
                    'msg' => '获取session_key失败：' . $session['errmsg']
                ]);
            }

            // 2. 解密 encryptedData 获取手机号
            $decrypted = $miniProgram->encryptor->decryptData(
                $session['session_key'],
                $request->iv,
                $request->encryptedData
            );

            // 解密成功，返回手机号（decrypted 包含详细用户信息）
            return response()->json([
                'success' => true,
                'phoneNumber' => $decrypted['phoneNumber'], // 手机号
                'purePhoneNumber' => $decrypted['purePhoneNumber'], // 不带区号的手机号
                'countryCode' => $decrypted['countryCode'] // 国家码
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'msg' => '解密失败：' . $e->getMessage()
            ]);
        }
    }
}
